﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityComponentSystem.Framework.Systems;
using EntityComponentSystem.Framework;

namespace ECS.Demos.Tetris.Systems
{
    public class BlockConstraintSystem : EntitySystem, IAutoSystem
    {
        public override string Name
        {
            get { return "blockconstraint"; }
        }

        public string[] AutoMappedComponents { get { return new string[] { "constraint" }; } }

        protected override void ProcessEntity(GameEngine ge, int entity)
        {
            var constraint = ge.GetComponent(entity, "constraint");
            var parent = ge.GetEntityByTag(constraint["parent"]);

            var srcPosition = ge.GetComponent(entity, "position");
            var srcSize = ge.GetComponent(entity, "size");
            var dstPosition = ge.GetComponent(parent, "position");
            var dstSize = ge.GetComponent(parent, "size");


            int sx1 = srcPosition["x"];
            int sy1 = srcPosition["y"];
            int sx2 = srcSize["width"] + sx1;
            int sy2 = srcSize["height"] + sy1;

            int dx1 = dstPosition["x"] + 1;
            int dy1 = dstPosition["y"] + 1;
            int dx2 = dstSize["width"] + dx1 - 2;
            int dy2 = dstSize["height"] + dy1 - 2;

            if (sx1 < dx1) srcPosition["x"] = dx1;
            if (sx2 > dx2) srcPosition["x"] = dx2 - srcSize["width"];
            if (sy1 < dy1) srcPosition["y"] = dy1 ;
            if (sy2 > dy2) srcPosition["y"] = dy2 - srcSize["height"];
        }
    }
}
